const { conn } = require('../gather/mongo');
const { getPageNum } = require('../utils/getpageNum');
exports.getBackground = (req, res) => {
    let { pageNum, pageSize } = req.query;
    let page = getPageNum(pageNum, pageSize);
    // 查询数据总数
    const sql1 = `SELECT COUNT(*) FROM bg_list`;
    conn.query(sql1, (err, result1) => {
        const sql = `SELECT * FROM bg_list LIMIT ${page},${pageSize} `;
        conn.query(sql, (err, result) => {
            if (err) {
                console.log(err);
                res.json({
                    code: 500,
                    msg: '数据库查询失败'
                })
            } else {
                res.json({
                    code: 200,
                    msg: '查询成功',
                    data: result,
                    total: result1[0]['COUNT(*)']
                })
            }
        })
    })

}

// 添加背景图
exports.addBackground = (req, res) => {
    let { imgName, imgUrl } = req.body;
    console.log(imgName, imgUrl);
    const sql = `INSERT INTO bg_list (bc_name,bc_url) VALUES ('${imgName}','${imgUrl}')`;
    conn.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            res.send({
                code: 500,
                msg: '添加背景失败'
            })
        } else {
            res.send({
                code: 200,
                msg: '添加背景成功'
            })
        }
    })
}
exports.delBg = (req, res) => {
    let { id, UserId } = req.body;
    let sql1 = `SELECT * FROM user_info where id=${UserId}`;
    conn.query(sql1, (err, result) => {
        if (result[0].roles != '超级管理员') return res.send({ code: 0, msg: '只有超级管理员才能删除哦！！' })
        let sql = `DELETE FROM bg_list where id=${id}`;
        conn.query(sql, (err, result) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 500,
                    msg: '删除背景失败'
                })
            } else {
                res.send({
                    code: 200,
                    msg: '删除背景成功'
                })
            }

        })
    })
}
// 选用背景后更新user  bc_url
exports.updateBack = (req, res) => {
    const { UserId, bcId } = req.body
    const sql = `SELECT * FROM bg_list WHERE id = ${bcId}`
    conn.query(sql, (err, result) => {
        console.log(result);
        if (err) {
            console.log(err)
        } else {
            const sql1 = `UPDATE user_info SET bg_url ='${result[0].bc_url}' WHERE id =${UserId}`
            conn.query(sql1, (err, result1) => {
                if (err) {
                    console.log(err)
                    res.send({
                        code: 500,
                        msg: '修改失败'
                    })
                } else {
                    res.send({
                        code: 200,
                        msg: '修改成功',
                        data: result[0]
                    })
                }
            })
        }

    })
}